<template>
  <div class="page-container">
    <el-card v-if="event" class="main-card">
      <template #header>
        <div class="card-header">
          <h3>{{ event.name }} <el-tag size="small">{{ categoryName }}</el-tag></h3>
          <div>
            <el-button @click="goToCustomNodes">自定义节点管理</el-button>
            <el-button type="primary" @click="editEventInfo">编辑信息</el-button>
            <el-button type="success" @click="runEvent">运行事件</el-button>
          </div>
        </div>
      </template>
      
      <el-descriptions title="基本信息" :column="3" border class="info-block">
        <el-descriptions-item label="事件ID">{{ event.id }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ event.createTime }}</el-descriptions-item>
        <el-descriptions-item label="分类">{{ categoryName }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="3">{{ event.description }}</el-descriptions-item>
      </el-descriptions>
      
      <!-- 事件局部变量组件 -->
      <EventVariables :event-id="event.id" class="variables-block" />
      
      <div class="event-flow-section">
        <div class="section-header">
          <h4>事件流</h4>
          <div>
            <el-switch
              v-model="draggableEnabled"
              active-text="拖拽排序"
              inactive-text="正常模式"
              style="margin-right: 10px;"
            />
            <el-button type="primary" size="small" @click="addNode">添加节点</el-button>
          </div>
        </div>
        
        <div class="flow-container" ref="flowContainer">
          <div v-if="event.nodes && event.nodes.length > 0" class="nodes-container">
            <draggable 
              v-model="event.nodes" 
              item-key="id"
              :disabled="!draggableEnabled"
              handle=".drag-handle"
              @end="handleDragEnd"
              ghost-class="ghost-node"
            >
              <template #item="{element, index}">
                <div class="node-item">
                  <div class="node">
                    <div class="node-header">
                      <div class="node-title">
                        <el-icon v-if="draggableEnabled" class="drag-handle"><el-icon-rank /></el-icon>
                        {{ index + 1 }}. {{ element.name }}
                      </div>
                      <div class="node-actions">
                        <el-button circle size="small" type="primary" @click="editNode(element, index)">
                          <el-icon><el-icon-edit /></el-icon>
                        </el-button>
                        <el-button circle size="small" type="danger" @click="removeNode(index)">
                          <el-icon><el-icon-delete /></el-icon>
                        </el-button>
                      </div>
                    </div>
                    <div class="node-content">
                      <el-tag size="small">{{ getNodeTypeName(element.type) }}</el-tag>
                      <div class="node-description">{{ element.description || '无描述' }}</div>
                    </div>
                  </div>
                  <div class="node-connector" v-if="index < event.nodes.length - 1">
                    <el-icon><el-icon-arrow-down /></el-icon>
                    <el-button 
                      size="small" 
                      type="primary" 
                      circle 
                      class="insert-node-btn"
                      @click="insertNodeAt(index + 1)" 
                      title="在此处插入节点"
                    >
                      <el-icon><el-icon-plus /></el-icon>
                    </el-button>
                  </div>
                </div>
              </template>
            </draggable>
          </div>
          <el-empty v-else description="暂无节点，请添加节点" />
        </div>
      </div>
    </el-card>
    
    <el-skeleton v-else :rows="10" animated />
    
    <!-- 编辑事件信息弹窗 -->
    <el-dialog
      v-model="editEventDialogVisible"
      title="编辑事件信息"
      width="500px"
    >
      <el-form :model="eventForm" label-width="80px" ref="eventFormRef" :rules="eventRules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="eventForm.name" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="eventForm.categoryId" placeholder="选择分类" style="width: 100%">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="eventForm.description" type="textarea" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editEventDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateEventInfo" :loading="submitting">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 节点编辑弹窗 -->
    <el-dialog
      v-model="nodeDialogVisible"
      :title="isEditingNode ? '编辑节点' : '添加节点'"
      width="800px"
    >
      <el-form :model="nodeForm" label-width="200px" ref="nodeFormRef" :rules="nodeRules">
        <el-form-item label="节点名称" prop="name" class="node-name-item">
          <el-input 
            v-model="nodeForm.name" 
            placeholder="请输入节点名称" 
            size="large"
            clearable
          />
        </el-form-item>
        <el-form-item label="节点类型" prop="type">
          <el-select v-model="nodeForm.type" placeholder="选择节点类型" style="width: 100%">
            <el-option label="开始" value="start" />
            <el-option label="结束" value="end" />
            <el-option label="输出文本" value="output" />
            <el-option label="条件判断" value="condition" />
            <el-option label="用户输入" value="input" />
            <el-option label="用户选择" value="select" />
            <el-option label="数字计算" value="calculation" />
            <el-option label="自定义执行" value="custom" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="nodeForm.description" type="textarea" rows="2" />
        </el-form-item>
        
        <!-- 根据节点类型显示不同的配置 -->
        <template v-if="nodeForm.type === 'output'">
          <el-form-item label="输出内容" prop="content">
            <InputWithVariable 
              :event-id="event.id" 
              field-name="content" 
              :model-value="nodeForm.content"
              @insert-variable="insertVariable"
            >
              <el-input v-model="nodeForm.content" type="textarea" rows="3" />
            </InputWithVariable>
          </el-form-item>

          <!-- 添加多目标选项 -->
          <el-divider>多分支设置</el-divider>
          <el-form-item label="分支选项">
            <div class="multi-target-container">
              <p class="form-help-text">添加多个分支选项，可以在运行时选择跳转到不同的节点</p>
              
              <div v-if="nodeForm.targets.length === 0" class="empty-targets">
                <el-empty description="暂无分支选项" :image-size="60">
                  <el-button type="primary" @click="addTarget">添加分支</el-button>
                </el-empty>
              </div>
              
              <div v-else>
                <div 
                  v-for="(target, idx) in nodeForm.targets" 
                  :key="idx" 
                  class="target-item"
                >
                  <el-row :gutter="10" style="width: 100%;">
                    <el-col :span="10">
                      <el-input v-model="target.label" placeholder="分支名称/描述" />
                    </el-col>
                    <el-col :span="10">
                      <el-select 
                        v-model="target.target" 
                        placeholder="选择目标节点" 
                        style="width: 100%;"
                      >
                        <el-option 
                          v-for="item in availableTargetNodes" 
                          :key="item.node.id" 
                          :label="`${item.index + 1}. ${item.node.name}`"
                          :value="item.index.toString()"
                          :disabled="item.disabled"
                        />
                      </el-select>
                    </el-col>
                    <el-col :span="4" style="display: flex; justify-content: flex-end;">
                      <el-button type="danger" circle @click="removeTarget(idx)">
                        <el-icon><el-icon-delete /></el-icon>
                      </el-button>
                    </el-col>
                  </el-row>
                </div>
                
                <div style="margin-top: 10px;">
                  <el-button type="primary" @click="addTarget">添加分支</el-button>
                </div>
              </div>
            </div>
          </el-form-item>
        </template>
        
        <template v-if="nodeForm.type === 'condition'">
          <el-form-item label="条件表达式" prop="condition">
            <InputWithVariable 
              :event-id="event.id" 
              field-name="condition" 
              :model-value="nodeForm.condition"
              @insert-variable="insertVariable"
            >
              <el-input v-model="nodeForm.condition" placeholder="例如: ${value} > 10" />
            </InputWithVariable>
          </el-form-item>
          <el-form-item label="条件为真时">
            <el-select v-model="nodeForm.trueTarget" placeholder="选择要跳转的节点" style="width: 100%">
              <el-option 
                v-for="item in availableTargetNodes" 
                :key="`true-${item.node.id}`" 
                :label="`${item.index + 1}. ${item.node.name}`"
                :value="item.index.toString()"
                :disabled="item.disabled"
              />
              <el-option label="下一个节点（默认）" value="" />
            </el-select>
            <div class="form-help-text">不选择表示继续执行下一个节点</div>
          </el-form-item>
          <el-form-item label="条件为假时">
            <el-select v-model="nodeForm.falseTarget" placeholder="选择要跳转的节点" style="width: 100%">
              <el-option 
                v-for="item in availableTargetNodes" 
                :key="`false-${item.node.id}`" 
                :label="`${item.index + 1}. ${item.node.name}`"
                :value="item.index.toString()"
                :disabled="item.disabled"
              />
              <el-option label="下一个节点（默认）" value="" />
            </el-select>
            <div class="form-help-text">不选择表示继续执行下一个节点</div>
          </el-form-item>
        </template>
        
        <template v-if="nodeForm.type === 'input'">
          <el-form-item label="提示文本" prop="prompt">
            <InputWithVariable 
              :event-id="event.id" 
              field-name="prompt" 
              :model-value="nodeForm.prompt"
              @insert-variable="insertVariable"
            >
              <el-input v-model="nodeForm.prompt" />
            </InputWithVariable>
          </el-form-item>
          <el-form-item label="变量名" prop="variableName">
            <el-input v-model="nodeForm.variableName" placeholder="存储输入值的变量名" />
            <div class="form-help-text">
              该变量将作为事件局部变量自动创建
            </div>
          </el-form-item>
        </template>
        
        <template v-if="nodeForm.type === 'select'">
          <el-form-item label="提示文本" prop="prompt">
            <InputWithVariable 
              :event-id="event.id" 
              field-name="prompt" 
              :model-value="nodeForm.prompt"
              @insert-variable="insertVariable"
            >
              <el-input v-model="nodeForm.prompt" />
            </InputWithVariable>
          </el-form-item>
          <el-form-item label="选项" prop="options">
            <el-row v-for="(option, idx) in nodeForm.options" :key="idx" :gutter="10" style="margin-bottom: 10px">
              <el-col :span="18">
                <el-input v-model="nodeForm.options[idx].label" placeholder="选项文本" />
              </el-col>
              <el-col :span="4">
                <el-input v-model="nodeForm.options[idx].value" placeholder="值" />
              </el-col>
              <el-col :span="2">
                <el-button type="danger" circle @click="removeOption(idx)">
                  <el-icon><el-icon-delete /></el-icon>
                </el-button>
              </el-col>
            </el-row>
            <el-button type="primary" @click="addOption">添加选项</el-button>
          </el-form-item>
          <el-form-item label="变量名" prop="variableName">
            <el-input v-model="nodeForm.variableName" placeholder="存储选择值的变量名" />
            <div class="form-help-text">
              该变量将作为事件局部变量自动创建
            </div>
          </el-form-item>
        </template>
        
        <!-- 数字计算节点配置 -->
        <template v-if="nodeForm.type === 'calculation'">
          <el-form-item label="计算表达式" prop="expression">
            <InputWithVariable 
              :event-id="event.id" 
              field-name="expression" 
              :model-value="nodeForm.expression"
              @insert-variable="insertVariable"
            >
              <el-input v-model="nodeForm.expression" placeholder="例如: ${num1} + ${num2} * 2" />
            </InputWithVariable>
            <div class="form-help-text">
              可以使用 ${变量名} 引用变量，支持 +, -, *, / 运算符和括号
            </div>
          </el-form-item>
          <el-form-item label="结果变量名" prop="resultVariable">
            <el-input v-model="nodeForm.resultVariable" placeholder="存储计算结果的变量名" />
            <div class="form-help-text">
              该变量将作为事件局部变量自动创建或更新
            </div>
          </el-form-item>
        </template>
        
        <!-- 自定义执行节点配置 -->
        <template v-if="nodeForm.type === 'custom'">
          <el-form-item label="自定义节点类型" prop="customNodeTypeId">
            <el-select 
              v-model="nodeForm.customNodeTypeId" 
              placeholder="选择自定义节点类型" 
              style="width: 100%"
              @change="handleCustomNodeTypeChange"
            >
              <el-option 
                v-for="item in publishedCustomNodeTypes" 
                :key="item.id" 
                :label="item.name" 
                :value="item.id"
              >
                <div class="custom-node-option">
                  <span class="custom-node-name">{{ item.name }}</span>
                  <div class="custom-node-meta">
                    <el-tag size="small" type="success" class="version-tag">v{{ item.version }}</el-tag>
                    <el-tooltip content="发布时间: {{ item.publishTime }}" placement="top">
                      <el-icon class="info-icon"><el-icon-info-filled /></el-icon>
                    </el-tooltip>
                  </div>
                </div>
              </el-option>
              <el-option label="自定义代码" value="">
                <div class="custom-node-option">
                  <span class="custom-node-name">
                    <el-icon><el-icon-edit /></el-icon> 自定义代码
                  </span>
                </div>
              </el-option>
            </el-select>
            <div class="form-help-text">
              选择已发布的自定义节点类型，或选择"自定义代码"直接编写代码
            </div>
          </el-form-item>
          
          <el-form-item label="执行代码" prop="customCode" v-if="!nodeForm.customNodeTypeId">
            <div class="code-examples-bar">
              <span>选择示例: </span>
              <el-select v-model="selectedExample" placeholder="选择示例代码" style="width: 200px;" @change="applyExampleCode">
                <el-option label="--无--" value="" />
                <el-option label="基本字符串处理" value="stringProcessingExample" />
                <el-option label="数学计算" value="mathCalculationExample" />
                <el-option label="异步操作示例" value="asyncOperationExample" />
                <el-option label="数组处理" value="arrayProcessingExample" />
                <el-option label="JSON解析与处理" value="jsonProcessingExample" />
              </el-select>
            </div>
            <el-input 
              v-model="nodeForm.customCode" 
              type="textarea" 
              rows="8" 
              placeholder="编写JavaScript代码，可以使用async/await"
            />
            <div class="form-help-text">
              <p>编写可执行的JavaScript代码。您的函数需要:</p>
              <ul class="code-help-list">
                <li>使用function(params){}或(params)=>{}格式定义</li>
                <li>params参数包含传入的所有参数值</li>
                <li>支持异步执行，可以使用async/await</li>
                <li>通过return返回结果</li>
              </ul>
            </div>
          </el-form-item>
          
          <template v-if="nodeForm.customNodeTypeId">
            <el-form-item label="节点说明">
              <div class="node-type-info">
                <div v-if="getCustomNodeTypeById(nodeForm.customNodeTypeId)?.description" class="node-info-section">
                  <h4 class="node-info-title">描述</h4>
                  <div class="info-content">{{ getCustomNodeTypeById(nodeForm.customNodeTypeId)?.description }}</div>
                </div>
                <div v-if="getCustomNodeTypeById(nodeForm.customNodeTypeId)?.parametersDocs" class="node-info-section">
                  <h4 class="node-info-title">参数说明</h4>
                  <div class="info-content">{{ getCustomNodeTypeById(nodeForm.customNodeTypeId)?.parametersDocs }}</div>
                </div>
                <div v-if="getCustomNodeTypeById(nodeForm.customNodeTypeId)?.returnDocs" class="node-info-section">
                  <h4 class="node-info-title">返回值说明</h4>
                  <div class="info-content">{{ getCustomNodeTypeById(nodeForm.customNodeTypeId)?.returnDocs }}</div>
                </div>
              </div>
            </el-form-item>
          </template>
          
          <el-divider content-position="left">
            <span class="divider-content">参数定义</span>
          </el-divider>
          
          <div class="custom-params-section">
            <div v-for="(param, idx) in nodeForm.customParams || []" :key="idx" class="param-item">
              <div class="param-header">
                <span class="param-index">参数 {{ idx+1 }}</span>
                <el-button type="danger" circle size="small" @click="removeCustomParam(idx)">
                  <el-icon><el-icon-delete /></el-icon>
                </el-button>
              </div>
              
              <el-row :gutter="15">
                <el-col :span="8">
                  <el-form-item label="参数名称" :prop="`customParams.${idx}.name`" label-position="top">
                    <el-input v-model="nodeForm.customParams[idx].name" placeholder="参数名称" />
                  </el-form-item>
                </el-col>
                
                <el-col :span="10">
                  <el-form-item label="参数值" :prop="`customParams.${idx}.value`" label-position="top">
                    <InputWithVariable 
                      :event-id="event.id" 
                      :field-name="`customParams.${idx}.value`" 
                      :model-value="nodeForm.customParams[idx].value"
                      @insert-variable="insertVariable"
                    >
                      <el-input v-model="nodeForm.customParams[idx].value" placeholder="参数值或${变量}" />
                    </InputWithVariable>
                  </el-form-item>
                </el-col>
                
                <el-col :span="6">
                  <el-form-item label="参数类型" :prop="`customParams.${idx}.type`" label-position="top">
                    <el-select v-model="nodeForm.customParams[idx].type" placeholder="类型" style="width: 100%">
                      <el-option label="字符串" value="string" />
                      <el-option label="数字" value="number" />
                      <el-option label="布尔值" value="boolean" />
                      <el-option label="对象" value="object" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            
            <div v-if="(nodeForm.customParams || []).length === 0" class="empty-params">
              <el-empty description="暂无参数" :image-size="60">
                <el-button type="primary" @click="addCustomParam">添加参数</el-button>
              </el-empty>
            </div>
            <div v-else class="add-param-btn">
              <el-button type="primary" size="large" icon-position="left" @click="addCustomParam">
                <el-icon><el-icon-plus /></el-icon>添加参数
              </el-button>
            </div>
          </div>
          
          <el-divider content-position="left">结果配置</el-divider>
          
          <el-form-item label="结果变量名" prop="resultVariable">
            <el-input v-model="nodeForm.resultVariable" placeholder="存储执行结果的变量名" />
            <div class="form-help-text">
              执行结果将保存到此变量中，可在后续节点中引用
            </div>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="nodeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveNode" :loading="submitting">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Edit as ElIconEdit, 
  Delete as ElIconDelete, 
  ArrowDown as ElIconArrowDown, 
  Plus as ElIconPlus,
  Rank as ElIconRank,
  InfoFilled as ElIconInfo
} from '@element-plus/icons-vue'
import EventVariables from '../components/EventVariables.vue'
import VariableSelector from '../components/VariableSelector.vue'
import InputWithVariable from '../components/InputWithVariable.vue'
import draggable from 'vuedraggable'
import { customNodeExamples } from '../examples/customNodeExamples'

const store = useStore()
const router = useRouter()
const route = useRoute()

const loading = ref(false)
const submitting = ref(false)
const editEventDialogVisible = ref(false)
const nodeDialogVisible = ref(false)
const eventFormRef = ref(null)
const nodeFormRef = ref(null)
const isEditingNode = ref(false)
const currentNodeIndex = ref(-1)
const flowContainer = ref(null)
const draggableEnabled = ref(false)
const selectedExample = ref('')

const eventForm = ref({
  name: '',
  categoryId: '',
  description: ''
})

const nodeForm = ref({
  name: '',
  type: 'output',
  description: '',
  content: '',
  condition: '',
  trueTarget: '',
  falseTarget: '',
  prompt: '',
  variableName: '',
  options: [],
  expression: '',
  resultVariable: '',
  targets: [],
  customCode: '',
  customParams: [],
  customNodeTypeId: ''
})

const eventRules = {
  name: [{ required: true, message: '请输入事件名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }]
}

const nodeRules = {
  name: [{ required: true, message: '请输入节点名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择节点类型', trigger: 'change' }],
  expression: [
    { required: true, message: '请输入计算表达式', trigger: 'blur', 
      validator: (rule, value, callback) => {
        if (nodeForm.value.type === 'calculation' && !value) {
          callback(new Error('请输入计算表达式'))
        } else {
          callback()
        }
      }
    }
  ],
  resultVariable: [
    { required: true, message: '请输入结果变量名', trigger: 'blur',
      validator: (rule, value, callback) => {
        if ((nodeForm.value.type === 'calculation' || nodeForm.value.type === 'custom') && !value) {
          callback(new Error('请输入结果变量名'))
        } else {
          callback()
        }
      }
    }
  ],
  customCode: [
    { required: true, message: '请输入执行代码', trigger: 'blur',
      validator: (rule, value, callback) => {
        if (nodeForm.value.type === 'custom' && !value) {
          callback(new Error('请输入执行代码'))
        } else {
          callback()
        }
      }
    }
  ]
}

const categories = computed(() => store.state.categories)

const event = computed(() => store.state.currentEvent)

const customNodeTypes = computed(() => store.state.customNodeTypes)

// 可用作跳转目标的节点列表（排除当前节点）
const availableTargetNodes = computed(() => {
  if (!event.value || !event.value.nodes) return []
  
  return event.value.nodes.map((node, index) => {
    // 如果正在编辑节点且为当前节点，标记为不可选
    const isCurrentNode = isEditingNode.value && index === currentNodeIndex.value
    return {
      node,
      index,
      disabled: isCurrentNode
    }
  })
})

const categoryName = computed(() => {
  if (!event.value) return ''
  const category = categories.value.find(c => c.id === event.value.categoryId)
  return category ? category.name : '未分类'
})

const getNodeTypeName = (type) => {
  const types = {
    'start': '开始',
    'end': '结束',
    'output': '输出文本',
    'condition': '条件判断',
    'input': '用户输入',
    'select': '用户选择',
    'calculation': '数字计算'
  }
  return types[type] || type
}

const fetchEvent = async () => {
  loading.value = true
  try {
    await store.dispatch('fetchEventById', route.params.id)
    await store.dispatch('fetchCategories')
    
    // 加载已发布的自定义节点类型
    await store.dispatch('fetchPublishedVersions')
  } catch (error) {
    ElMessage.error('获取事件详情失败')
  } finally {
    loading.value = false
  }
}

const editEventInfo = () => {
  if (!event.value) return
  
  eventForm.value = {
    name: event.value.name,
    categoryId: event.value.categoryId,
    description: event.value.description
  }
  
  editEventDialogVisible.value = true
}

const updateEventInfo = async () => {
  if (!eventFormRef.value) return
  
  await eventFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const updatedEvent = {
          ...event.value,
          ...eventForm.value
        }
        await store.dispatch('updateEvent', { id: event.value.id, event: updatedEvent })
        ElMessage.success('更新成功')
        editEventDialogVisible.value = false
      } catch (error) {
        ElMessage.error('更新失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

const addNode = async () => {
  nodeForm.value = {
    name: '',
    type: 'output',
    description: '',
    content: '',
    condition: '',
    trueTarget: '',
    falseTarget: '',
    prompt: '',
    variableName: '',
    options: [],
    expression: '',
    resultVariable: '',
    targets: [],
    customCode: '',
    customParams: [],
    customNodeTypeId: ''
  }
  
  isEditingNode.value = false
  currentNodeIndex.value = -1
  
  // 先加载可用变量，然后再打开对话框
  try {
    loading.value = true
    await store.dispatch('fetchAllAvailableVariables', event.value.id)
  } catch (error) {
    console.error('加载变量失败:', error)
  } finally {
    loading.value = false
    // 确保变量加载完成后再打开对话框
    nodeDialogVisible.value = true
  }
}

const editNode = async (node, index) => {
  // 深拷贝节点数据
  nodeForm.value = JSON.parse(JSON.stringify(node))
  
  // 如果是select类型但没有options，初始化一个空数组
  if (!nodeForm.value.options && nodeForm.value.type === 'select') {
    nodeForm.value.options = []
  }
  
  isEditingNode.value = true
  currentNodeIndex.value = index
  
  // 先加载可用变量，然后再打开对话框
  try {
    loading.value = true
    await store.dispatch('fetchAllAvailableVariables', event.value.id)
  } catch (error) {
    console.error('加载变量失败:', error)
  } finally {
    loading.value = false
    // 确保变量加载完成后再打开对话框
    nodeDialogVisible.value = true
  }
}

const insertNodeAt = async (index) => {
  nodeForm.value = {
    name: '',
    type: 'output',
    description: '',
    content: '',
    condition: '',
    trueTarget: '',
    falseTarget: '',
    prompt: '',
    variableName: '',
    options: [],
    expression: '',
    resultVariable: '',
    targets: [],
    customCode: '',
    customParams: [],
    customNodeTypeId: ''
  }
  
  isEditingNode.value = false
  currentNodeIndex.value = index
  
  // 先加载可用变量，然后再打开对话框
  try {
    loading.value = true
    await store.dispatch('fetchAllAvailableVariables', event.value.id)
  } catch (error) {
    console.error('加载变量失败:', error)
  } finally {
    loading.value = false
    // 确保变量加载完成后再打开对话框
    nodeDialogVisible.value = true
  }
}

const saveNode = async () => {
  if (!nodeFormRef.value) return
  
  await nodeFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const updatedEvent = { ...event.value }
        
        if (!updatedEvent.nodes) {
          updatedEvent.nodes = []
        }
        
        // 确保事件具有versionReferences字段
        if (!updatedEvent.versionReferences) {
          updatedEvent.versionReferences = []
        }
        
        const nodeData = { ...nodeForm.value, id: isEditingNode.value ? nodeForm.value.id : `node_${Date.now()}` }
        
        // 处理自定义节点的版本引用
        let oldNodeData = null
        if (isEditingNode.value && currentNodeIndex.value >= 0) {
          oldNodeData = updatedEvent.nodes[currentNodeIndex.value]
        }
        
        // 如果是编辑模式，先检查是否需要移除旧的自定义节点版本引用
        if (isEditingNode.value && oldNodeData && oldNodeData.type === 'custom' && 
            oldNodeData.customNodeTypeId && oldNodeData.customNodeVersionId) {
          // 检查新节点是否不再使用原来的自定义节点类型或版本已变更
          if (nodeData.type !== 'custom' || 
              nodeData.customNodeTypeId !== oldNodeData.customNodeTypeId) {
            
            // 检查是否还有其他节点使用这个版本
            const stillInUse = updatedEvent.nodes.some((node, idx) => 
              idx !== currentNodeIndex.value && 
              node.type === 'custom' && 
              node.customNodeTypeId === oldNodeData.customNodeTypeId &&
              node.customNodeVersionId === oldNodeData.customNodeVersionId
            )
            
            // 如果没有其他节点使用，从versionReferences中移除
            if (!stillInUse) {
              updatedEvent.versionReferences = updatedEvent.versionReferences.filter(ref => 
                !(ref.nodeTypeId === oldNodeData.customNodeTypeId && 
                  ref.versionId === oldNodeData.customNodeVersionId)
              )
            }
          }
        }
        
        // 如果是自定义节点类型，添加版本引用
        if (nodeData.type === 'custom' && nodeData.customNodeTypeId) {
          // 如果选择已发布的自定义节点类型，获取其版本ID
          const customNodeType = publishedCustomNodeTypes.value.find(
            item => item.nodeTypeId === nodeData.customNodeTypeId
          )
          
          if (customNodeType) {
            // 设置版本ID
            nodeData.customNodeVersionId = customNodeType.id
            
            // 检查引用是否已存在
            const versionRefExists = updatedEvent.versionReferences.some(ref => 
              ref.nodeTypeId === nodeData.customNodeTypeId && 
              ref.versionId === nodeData.customNodeVersionId
            )
            
            // 如果引用不存在，添加到versionReferences数组
            if (!versionRefExists) {
              updatedEvent.versionReferences.push({
                nodeTypeId: nodeData.customNodeTypeId,
                versionId: nodeData.customNodeVersionId
              })
            }
          }
        }
        
        if (isEditingNode.value) {
          updatedEvent.nodes[currentNodeIndex.value] = nodeData
        } else if (currentNodeIndex.value >= 0 && currentNodeIndex.value < updatedEvent.nodes.length) {
          updatedEvent.nodes.splice(currentNodeIndex.value, 0, nodeData)
        } else {
          updatedEvent.nodes.push(nodeData)
        }
        
        if (currentNodeIndex.value >= 0) {
          updatedEvent.nodes.forEach(node => {
            if (node.type === 'condition') {
              if (node.trueTarget && !isNaN(node.trueTarget) && parseInt(node.trueTarget) >= currentNodeIndex.value) {
                node.trueTarget = (parseInt(node.trueTarget) + 1).toString()
              }
              if (node.falseTarget && !isNaN(node.falseTarget) && parseInt(node.falseTarget) >= currentNodeIndex.value) {
                node.falseTarget = (parseInt(node.falseTarget) + 1).toString()
              }
            }
          })
        }
        
        await store.dispatch('updateEvent', { id: event.value.id, event: updatedEvent })
        ElMessage.success(isEditingNode.value ? '更新节点成功' : '添加节点成功')
        nodeDialogVisible.value = false
      } catch (error) {
        ElMessage.error(isEditingNode.value ? '更新节点失败' : '添加节点失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

const removeNode = (index) => {
  ElMessageBox.confirm('确认删除该节点？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const updatedEvent = { ...event.value }
      const nodeToRemove = updatedEvent.nodes[index]
      
      // 如果删除的是自定义节点，检查是否需要更新版本引用
      if (nodeToRemove.type === 'custom' && nodeToRemove.customNodeTypeId && nodeToRemove.customNodeVersionId) {
        // 确保versionReferences存在
        if (!updatedEvent.versionReferences) {
          updatedEvent.versionReferences = []
        }
        
        // 检查是否还有其他节点使用这个版本
        const stillInUse = updatedEvent.nodes.some((node, idx) => 
          idx !== index && 
          node.type === 'custom' && 
          node.customNodeTypeId === nodeToRemove.customNodeTypeId &&
          node.customNodeVersionId === nodeToRemove.customNodeVersionId
        )
        
        // 如果没有其他节点使用，从versionReferences中移除
        if (!stillInUse) {
          updatedEvent.versionReferences = updatedEvent.versionReferences.filter(ref => 
            !(ref.nodeTypeId === nodeToRemove.customNodeTypeId && 
              ref.versionId === nodeToRemove.customNodeVersionId)
          )
        }
      }
      
      // 从节点数组中移除节点
      updatedEvent.nodes.splice(index, 1)
      
      await store.dispatch('updateEvent', { id: event.value.id, event: updatedEvent })
      ElMessage.success('删除节点成功')
    } catch (error) {
      ElMessage.error('删除节点失败')
    }
  }).catch(() => {})
}

const addOption = () => {
  if (!nodeForm.value.options) {
    nodeForm.value.options = []
  }
  nodeForm.value.options.push({ label: '', value: '' })
}

const removeOption = (index) => {
  nodeForm.value.options.splice(index, 1)
}

const addTarget = () => {
  nodeForm.value.targets.push({
    label: '',
    target: ''
  })
}

const removeTarget = (index) => {
  nodeForm.value.targets.splice(index, 1)
}

const runEvent = () => {
  router.push(`/events/${event.value.id}/run`)
}

const insertVariable = (variable, fieldName) => {
  const varObj = typeof variable === 'object' && variable !== null ? variable : { name: variable }
  
  const cursorPosition = document.activeElement.selectionStart || 0
  const value = nodeForm[fieldName] || ''
  const variableRef = `\${${varObj.name}}`
  
  nodeForm[fieldName] = value.substring(0, cursorPosition) + 
    variableRef + 
    value.substring(cursorPosition)
}

// 处理拖拽结束事件
const handleDragEnd = async () => {
  // 更新所有条件节点的跳转索引
  if (event.value && event.value.nodes) {
    let nodeChanged = false
    
    // 检查每个条件节点的跳转目标，更新索引
    event.value.nodes.forEach((node, newIndex) => {
      if (node.type === 'condition') {
        // 找到每个节点在原始顺序中的位置，然后更新引用的节点
        if (node.trueTarget !== '' && node.trueTarget !== undefined) {
          const targetNodeId = getNodeIdByIndex(parseInt(node.trueTarget))
          if (targetNodeId) {
            const newTargetIndex = getNodeIndexById(targetNodeId)
            if (newTargetIndex !== parseInt(node.trueTarget)) {
              node.trueTarget = newTargetIndex.toString()
              nodeChanged = true
            }
          }
        }
        
        if (node.falseTarget !== '' && node.falseTarget !== undefined) {
          const targetNodeId = getNodeIdByIndex(parseInt(node.falseTarget))
          if (targetNodeId) {
            const newTargetIndex = getNodeIndexById(targetNodeId)
            if (newTargetIndex !== parseInt(node.falseTarget)) {
              node.falseTarget = newTargetIndex.toString()
              nodeChanged = true
            }
          }
        }
      }
    })
    
    if (nodeChanged) {
      try {
        await saveEvent()
        ElMessage.success('节点顺序已更新，条件跳转索引已自动调整')
      } catch (error) {
        ElMessage.error('保存节点顺序失败')
      }
    } else {
      await saveEvent()
      ElMessage.success('节点顺序已更新')
    }
  }
}

// 根据索引获取节点ID
const getNodeIdByIndex = (index) => {
  if (event.value && event.value.nodes && index >= 0 && index < event.value.nodes.length) {
    return event.value.nodes[index].id
  }
  return null
}

// 根据节点ID获取当前索引
const getNodeIndexById = (nodeId) => {
  if (event.value && event.value.nodes) {
    const index = event.value.nodes.findIndex(node => node.id === nodeId)
    return index
  }
  return -1
}

// 保存事件的辅助函数
const saveEvent = async () => {
  try {
    await store.dispatch('updateEvent', { 
      id: event.value.id, 
      event: event.value 
    })
    return true
  } catch (error) {
    console.error('保存事件失败:', error)
    return false
  }
}

const addCustomParam = () => {
  nodeForm.value.customParams.push({ name: '', value: '', type: 'string' })
}

const removeCustomParam = (index) => {
  nodeForm.value.customParams.splice(index, 1)
}

const applyExampleCode = () => {
  if (!selectedExample.value) return
  
  const example = customNodeExamples[selectedExample.value]
  if (example) {
    // 如果已有代码，确认是否覆盖
    if (nodeForm.value.customCode && nodeForm.value.customCode.trim() !== '') {
      ElMessageBox.confirm(
        '这将覆盖您当前的代码。是否继续?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        nodeForm.value.customCode = example
        
        // 根据示例类型添加示例参数
        if (selectedExample.value === 'stringProcessingExample') {
          nodeForm.value.customParams = [
            { name: 'text', value: '示例文本', type: 'string' }
          ]
        } else if (selectedExample.value === 'mathCalculationExample') {
          nodeForm.value.customParams = [
            { name: 'x', value: '10', type: 'number' },
            { name: 'y', value: '5', type: 'number' },
            { name: 'operation', value: 'add', type: 'string' }
          ]
        } else if (selectedExample.value === 'asyncOperationExample') {
          nodeForm.value.customParams = [
            { name: 'data', value: '示例数据', type: 'string' },
            { name: 'delay', value: '2000', type: 'number' }
          ]
        } else if (selectedExample.value === 'arrayProcessingExample') {
          nodeForm.value.customParams = [
            { name: 'array', value: '[1,2,3,4,5]', type: 'object' },
            { name: 'operation', value: 'sort', type: 'string' }
          ]
        } else if (selectedExample.value === 'jsonProcessingExample') {
          nodeForm.value.customParams = [
            { name: 'jsonData', value: '{"name":"测试","value":123}', type: 'object' },
            { name: 'operation', value: 'keys', type: 'string' }
          ]
        }
        
        ElMessage.success('已应用示例代码')
      }).catch(() => {
        // 用户取消
      })
    } else {
      nodeForm.value.customCode = example
      
      // 根据示例类型添加示例参数
      if (selectedExample.value === 'stringProcessingExample') {
        nodeForm.value.customParams = [
          { name: 'text', value: '示例文本', type: 'string' }
        ]
      } else if (selectedExample.value === 'mathCalculationExample') {
        nodeForm.value.customParams = [
          { name: 'x', value: '10', type: 'number' },
          { name: 'y', value: '5', type: 'number' },
          { name: 'operation', value: 'add', type: 'string' }
        ]
      } else if (selectedExample.value === 'asyncOperationExample') {
        nodeForm.value.customParams = [
          { name: 'data', value: '示例数据', type: 'string' },
          { name: 'delay', value: '2000', type: 'number' }
        ]
      } else if (selectedExample.value === 'arrayProcessingExample') {
        nodeForm.value.customParams = [
          { name: 'array', value: '[1,2,3,4,5]', type: 'object' },
          { name: 'operation', value: 'sort', type: 'string' }
        ]
      } else if (selectedExample.value === 'jsonProcessingExample') {
        nodeForm.value.customParams = [
          { name: 'jsonData', value: '{"name":"测试","value":123}', type: 'object' },
          { name: 'operation', value: 'keys', type: 'string' }
        ]
      }
      
      ElMessage.success('已应用示例代码')
    }
  }
}

// 获取已发布的自定义节点类型列表
const publishedCustomNodeTypes = computed(() => {
  return store.getters.getPublishedCustomNodeTypes || []
})

// 根据自定义节点类型ID获取节点类型信息
const getCustomNodeTypeById = (id) => {
  return publishedCustomNodeTypes.value.find(item => item.id === id)
}

// 当选择自定义节点类型时更新参数定义
const handleCustomNodeTypeChange = () => {
  // 如果没有选择自定义节点类型，清空参数
  if (!nodeForm.value.customNodeTypeId) {
    return
  }
  
  // 获取选择的自定义节点类型
  const nodeType = getCustomNodeTypeById(nodeForm.value.customNodeTypeId)
  if (!nodeType) return
  
  // 自动生成参数参考示例
  if (nodeType.parametersDocs) {
    // 检查是否已有参数，如果没有则创建示例参数
    if (nodeForm.value.customParams.length === 0) {
      // 尝试从参数说明中自动识别参数
      const paramNames = nodeType.parametersDocs.match(/\b\w+(?=\s*:)/g)
      if (paramNames && paramNames.length > 0) {
        // 为识别到的每个参数创建一个空参数
        nodeForm.value.customParams = paramNames.map(name => ({
          name,
          value: '',
          type: 'string'
        }))
      } else {
        // 如果没有识别到参数，添加一个默认的空参数
        nodeForm.value.customParams = [{ name: '', value: '', type: 'string' }]
      }
    }
  }
}

// 跳转到自定义节点管理页面
const goToCustomNodes = () => {
  router.push('/custom-nodes')
}

onMounted(() => {
  fetchEvent()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.main-card {
  margin-bottom: 30px;
}

.info-block {
  margin-bottom: 24px;
}

.variables-block {
  margin-bottom: 24px;
}

.event-flow-section {
  margin-top: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.flow-container {
  max-height: 70vh; /* 设置最大高度为视口高度的70% */
  overflow-y: auto; /* 启用垂直滚动 */
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f8f8f8;
}

.nodes-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px;
  width: 100%;
}

.node-item {
  position: relative;
  margin-bottom: 20px;
  width: 100%;
}

.node {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 14px;
  width: 100%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.node:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.node-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 8px;
}

.node-title {
  font-weight: bold;
  display: flex;
  align-items: center;
  font-size: 14px;
}

.node-actions {
  display: flex;
  gap: 8px;
}

.node-content {
  font-size: 13px;
  color: #606266;
}

.node-description {
  margin-top: 8px;
  line-height: 1.4;
}

.node-connector {
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 20px;
  position: relative;
  margin: 10px 0;
}

.insert-node-btn {
  position: absolute;
  transform: scale(0.8);
  opacity: 0;
  transition: opacity 0.2s;
}

.node-connector:hover .insert-node-btn {
  opacity: 1;
}

.input-with-variable {
  display: flex;
  align-items: center;
}

.form-help-text {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
  margin-top: 4px;
}

.drag-handle {
  cursor: move;
  margin-right: 5px;
  color: #909399;
}

.ghost-node {
  opacity: 0.5;
  background: #c8ebfb;
  border: 1px dashed #409eff;
}

.multi-target-container {
  margin-top: 10px;
}

.target-item {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f8f9fa;
}

.empty-targets {
  padding: 20px;
  text-align: center;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .nodes-container {
    grid-template-columns: 1fr;
  }
}

@media screen and (min-width: 1200px) {
  .nodes-container {
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  }
}

.event-edit-container {
  max-width: 1200px;
  margin: 0 auto;
}

.edit-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.node-list {
  margin-top: 15px;
}

.node-item {
  margin-bottom: 10px;
}

.node {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  padding: 15px;
}

.node-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.node-title {
  font-weight: bold;
  display: flex;
  align-items: center;
}

.node-content {
  margin-top: 10px;
}

.node-description {
  margin-top: 10px;
  color: #606266;
}

.node-connector {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 5px 0;
  position: relative;
}

.insert-node-btn {
  margin-top: 5px;
}

.form-help-text {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.drag-handle {
  cursor: move;
  margin-right: 5px;
}

/* 自定义节点样式 */
.code-help-list {
  padding-left: 20px;
  margin: 5px 0;
}

.code-help-list li {
  font-size: 12px;
  margin-bottom: 3px;
}

.param-item {
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  padding: 18px;
  margin-bottom: 20px;
  background-color: #fcfcfc;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  position: relative;
}

.param-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.param-index {
  font-weight: 600;
  color: #409eff;
  font-size: 15px;
  display: flex;
  align-items: center;
}

.param-index::before {
  content: '';
  display: inline-block;
  width: 3px;
  height: 16px;
  background-color: #409eff;
  margin-right: 8px;
  border-radius: 2px;
}

.param-item:hover {
  border-color: #c0c4cc;
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
  background-color: #f8faff;
}

.param-item .el-form-item {
  margin-bottom: 0;
}

.param-item .el-form-item__label {
  padding-bottom: 6px;
  font-weight: 500;
  color: #606266;
}

.custom-params-section {
  margin: 15px 0 25px;
  background-color: #f9fafc;
  border-radius: 8px;
  padding: 20px;
}

.divider-content {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.add-param-btn {
  margin-top: 15px;
  text-align: center;
  display: flex;
  justify-content: center;
}

.empty-params {
  padding: 30px 20px;
  background-color: #fcfcfc;
  border-radius: 6px;
  border: 1px dashed #dcdfe6;
}

.code-examples-bar {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.node-type-info {
  background-color: #f9fafc;
  border-radius: 6px;
  padding: 12px 16px;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.node-info-section {
  margin-bottom: 16px;
  background-color: #fff;
  border-radius: 4px;
  padding: 10px 12px;
  border: 1px solid #f0f2f5;
}

.node-info-section:last-child {
  margin-bottom: 0;
}

.node-info-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 8px;
  display: flex;
  align-items: center;
}

.node-info-title::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 14px;
  background-color: #409eff;
  margin-right: 8px;
  border-radius: 2px;
}

.info-content {
  margin-top: 5px;
  font-size: 13px;
  color: #606266;
  line-height: 1.6;
  white-space: pre-line;
}

.info-icon {
  margin-left: 5px;
  color: #909399;
  font-size: 14px;
  cursor: help;
}

.custom-node-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 4px 0;
}

.el-select-dropdown__item:hover .custom-node-option {
  transition: all 0.2s;
}

.el-select-dropdown__item.selected .custom-node-name {
  color: #409eff;
  font-weight: 600;
}

.custom-node-name {
  font-weight: 500;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 5px;
}

.custom-node-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.version-tag {
  font-size: 11px;
  height: 20px;
  line-height: 18px;
  padding: 0 6px;
}

.param-form-items {
  display: none;
}

.node-name-item {
  margin-bottom: 18px;
}

.node-name-item :deep(.el-input__wrapper) {
  padding: 4px 12px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.node-name-item :deep(.el-input__inner) {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  height: 46px;
}

.node-name-item :deep(.el-form-item__label) {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  padding-bottom: 8px;
}
</style> 